//
//  GXGameView.swift
//  GameCatchBall
//
//  Created by GuangXiao on 16/1/19.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
import SnapKit

class GXGameView: UIView {
    //提取状态栏高度
    let statusBarHeight = 20
    //图片的宽高 用于确定图片center出现的位置
    let buttonWH:CGFloat = 34
    //scoreLabel的高度
    let scoreLabelHeight : CGFloat = 35
    
    let standardPercentage : CGFloat = 0.5
    //游戏是否结束的状态
    var isGameOver:Bool = false
    //进度条的约束
    var progressViewTopConstraint : Constraint?
    //全局定时器
    var timer:NSTimer?
    
    //属性赋值中的逻辑实现
    //没捕获的数量
    var missCount:Int = 0{
        didSet{
            self.missLabel.text = "逃跑:\(missCount)只"
            
            percentage = CGFloat(catchCount) / CGFloat(missCount + catchCount)
        }
    }
    //捕获的数量
    var catchCount:Int = 0{
        didSet{
            percentage = CGFloat(catchCount) / CGFloat(missCount + catchCount)
        }
    }
    //捕获率
    var percentage:CGFloat = 1.0{
        didSet{

            //更新约束前 卸载约束
            self.progressViewTopConstraint?.uninstall()
            progressViewTop.snp_updateConstraints { (make) -> Void in
                
                make.width.equalTo(120 * percentage)
            }
            
            let str = String(format: "%.2f", percentage * 100)
            self.progressLabel.text = str + "%"
            print(self.progressLabel.text!)
            //如果捕获率低于百分之八十 游戏结束
            if self.percentage <= standardPercentage{
                gameOver()
            }
        }
    }
    //默认分数是0分
    var score:CGFloat = 0.0{
        didSet{
            
            let str = String(format: "%.2f", score)
            self.scoreLabel.text = "分数:" + str
            
            if score > recordScore {
                recordScore = score
            }
        }
    }
    
    //最高分
    var recordScore:CGFloat = 0.0{
        didSet{
            let str = String(format: "%.2f", recordScore)
            self.recordLabel.text = "最高分:" + str + "分"
            
        }
    }
    
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        //读取最高分
        readRecordSocre()
        
        let myTimer = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "generateImage", userInfo: nil, repeats: true)
        timer = myTimer
        
        //程序初始化时调用一次 使view满格
//        progressView.progress = 1.0
    }
    
    /**
     随机位置 添加随机数量的图片按钮
     */
    @objc private func generateImage(){
        //==================随机位置的范围=================
        //x的范围 (0 到屏幕宽度减去button自身的宽度)
        let xScopeStop = Int(ScreenWidth - buttonWH)
        
        //y的范围 （状态栏的底部 到 屏幕高度减去 scoreLabel的高度 再减去自身的高度）
        let yScopeBegin = statusBarHeight + 44 + 6 + 10
        let yScopeStop = Int(ScreenHeight - scoreLabelHeight - buttonWH)
        //================随机数量图片的添加=============
        //生成imageView的数量（添加1到4各图片）
        
        // 3 - 5
        let imageCount = arc4random() % 4 + 1
        
        //==========随机位置添加图片 并记录总共产生的数量
        for _ in 0..<imageCount{
            //生成随机point
            let x = CGFloat(arc4random() % UInt32(xScopeStop))
            let y = CGFloat((arc4random() % UInt32(yScopeStop - yScopeBegin)) + UInt32(yScopeBegin))
            
            //初始化button 并添加到view上
            let imageButton = GXButton()
            addSubview(imageButton)
            
            //添加到imagebutton数组中
            //            imageButtons.append(imageButton)
            //设置button的frame  主要是随机的位置信息
            var buttonFrame = imageButton.frame
            buttonFrame.origin = CGPointMake(x, y)
            imageButton.frame = buttonFrame
            
            //button的点击事件
            imageButton.addTarget(self, action: "buttonClick:", forControlEvents: .TouchUpInside)
            
            //3秒后 如果button未被选中，就移除该button 并将移除数量加一
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(3 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(),{
                
                //如果游戏仍在继续
                if self.percentage >= self.standardPercentage {
                    //如果游戏没有结束 为防止游戏过程中返回主页面
                    if !self.isGameOver{
                    //如果button为未选中状态
                        if !imageButton.selected {
                            imageButton.removeFromSuperview()
                            GXSoundManager().playSoundWithFileName("miss.mp3")
                            self.missCount += 1
                        }
                    }
                }
                
            });
        }
    }
    
    /**
     重新开始
     */
    @objc private func restart (){
        
        isGameOver = false
        //---------遮罩view 透明度变为0 并移除
        UIView.animateWithDuration(0.01, animations: { () -> Void in
            self.coverView.alpha = 0
            }) { (_) -> Void in
                self.coverView.removeFromSuperview()
        }
        //---------遍历view上的子控件 将所有button移除
        for value in self.subviews{
            if value.isKindOfClass(GXButton){
                value.removeFromSuperview()
            }
        }
        //---------初始化分数和逃跑数
        score = 0
        missCount = 0
        percentage = 1.0
        self.progressLabel.text = "100%"
        
        
        //---------重新添加计时器--------
        let myTimer = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "generateImage", userInfo: nil, repeats: true)
        timer = myTimer
        
        //-----------添加倒计时视图 并移除------
        addSubview(countDownView)
        countDownView.startCountdown()
        //两秒后移除
        UIView.animateWithDuration(2, animations: { () -> Void in
            self.countDownView.alpha = 0
            }) { (_) -> Void in
                
                self.countDownView.removeFromSuperview()
        }
        
    }
    
    /**
     保存最高分数
     */
    private func saveRecordScore(){

//        1.获取default对象,写入数据
        let userDefault = NSUserDefaults.standardUserDefaults()
//        //    2.设置数据
            userDefault.setValue(self.recordScore, forKey: "记录")

//        //    3.同步
        userDefault.synchronize()
    }
    
    /**
     读取沙盒中存储的最高分
     */
    private func readRecordSocre(){

        let userDefault = NSUserDefaults.standardUserDefaults()
        let score = userDefault.objectForKey("记录")
        guard let trueScore = score else{
            return
        }
        recordScore = CGFloat(trueScore.floatValue as NSNumber)
    }
    /**
     游戏结束
     */
     func gameOver(){
        //取消定时器 将定时器设为空
        timer?.invalidate()
        timer = nil
        

        //将游戏结束状态设置为真
        isGameOver = true
        //存储最高分
        saveRecordScore()
        
        coverView.addSubview(restartButton)
        coverView.addSubview(backHomeButton)
        restartButton.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(coverView.snp_centerX)
            make.centerY.equalTo(coverView.snp_centerY).offset(-15)
            make.size.equalTo(CGSizeMake(200, 30))
        }
        backHomeButton.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(restartButton.snp_centerX)
            make.top.equalTo(restartButton.snp_bottom).offset(8)
            make.size.equalTo(CGSizeMake(200, 30))
        }
        //        coverView.center = self.center
        self.addSubview(coverView)
        
        //销毁音效
        GXSoundManager().disposeMusicWithFileName("catched.mp3")
        GXSoundManager().disposeMusicWithFileName("miss.mp3")
        
    }
    
    /**
     点击小图片后调用的方法
     */
    @objc private func buttonClick(button:GXButton){
        
        //移除点击的button 分数加五*捕获率  捕获数量加一
        button.removeFromSuperview()
        GXSoundManager().playSoundWithFileName("catched.mp3")
        score += 5 * percentage
        catchCount += 1
        button.selected = true
    }
    
    
    /**
     返回主页
     */
    @objc private func backHome(){
        NSNotificationCenter.defaultCenter().postNotificationName("backHomeNotification", object: nil)
        
    }
    
    
    /**
     界面布局
     */
    private func setupUI(){
        backgroundColor = UIColor.whiteColor()
        
        addSubview(scoreLabel)
        addSubview(missLabel)
        addSubview(progressView)
        addSubview(progressViewTop)
        addSubview(progressLabel)
        addSubview(recordLabel)
        
        
        
        scoreLabel.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(self.snp_left)
            make.bottom.equalTo(self.snp_bottom)
            make.width.equalTo(missLabel.snp_width)
            make.height.equalTo(35)
        }
        missLabel.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(scoreLabel.snp_right)
            make.right.equalTo(self.snp_right)
            make.top.equalTo(scoreLabel.snp_top)
            make.height.equalTo(scoreLabel)
        }
        progressView.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(self.snp_left).offset(8)
            make.size.equalTo(CGSizeMake(120, 10))
            make.top.equalTo(self.snp_top).offset(70)
            
        }
        progressViewTop.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(self.snp_left).offset(8)
//            make.size.equalTo(CGSizeMake(120, 10))
            self.progressViewTopConstraint = make.width.equalTo(120).constraint
            make.height.equalTo(10)
            make.top.equalTo(self.snp_top).offset(70)
            
        }
        progressLabel.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(progressView.snp_centerY)
            make.left.equalTo(progressView.snp_right).offset(8)
        }
        
        recordLabel.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(progressLabel.snp_centerY)
            make.right.equalTo(self.snp_right).offset(-8)
        }
        
        
        addSubview(countDownView)
        countDownView.startCountdown()
        //两秒后移除
        UIView.animateWithDuration(2, animations: { () -> Void in
            self.countDownView.alpha = 0
            }) { (_) -> Void in
                
                self.countDownView.removeFromSuperview()
        }
    }
    
   
//    override func didMoveToWindow() {
//        print("yichu")
//    }
    //=====================控件懒加载================
    
    private lazy var recordLabel:UILabel = {
        let label = UILabel()
        label.text = "最高分:0分"
        label.textColor = UIColor.redColor()
        label.sizeToFit()
        return label
    }()
    //捕获率label
    private lazy var progressLabel:UILabel = {
        let label = UILabel()
        label.text = "100%"
        label.sizeToFit()
        
        return label
    }()
    //进度条
    private lazy var progressView:UIView = {
        let progressView = UIView()

        progressView.layer.cornerRadius = 5
        progressView.clipsToBounds = true
        progressView.backgroundColor = .redColor()
        
        return progressView
    }()
    private lazy var progressViewTop:UIView = {
        let progressViewTop = UIView()
        progressViewTop.layer.cornerRadius = 5
        progressViewTop.clipsToBounds = true
        progressViewTop.backgroundColor = .greenColor()
        
        return progressViewTop
    }()
    /// 分数label
    private lazy var scoreLabel:UILabel = {
        let label = UILabel()
        label.backgroundColor = UIColor.cyanColor()
        label.text = "分数:0"
        label.textAlignment = .Center
        return label
    }()
    /// 逃跑数量label
    private lazy var missLabel:UILabel = {
        let label = UILabel()
        label.backgroundColor = UIColor.yellowColor()
        label.text = "逃跑:0只"
        label.textAlignment = .Center
        return label
    }()
    
    /// gameover 的coverView
    private lazy var coverView:UIView = {
        
        let coverView = UIView(frame:CGRectMake(0, 64, ScreenWidth, ScreenHeight - 64 - self.scoreLabel.frame.size.height))
        coverView.backgroundColor = UIColor.darkGrayColor()
        coverView.alpha = 0.35
        return coverView
    }()
    
    /// gameover的重新开始的button
    private lazy var restartButton:UIButton = {
        let restartButton = UIButton()
        
        restartButton.bounds = CGRectMake(0,0,200,30)
        
        restartButton.setTitle("重新开始", forState: .Normal)
        restartButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
        restartButton.layer.borderWidth = 2.0
        restartButton.layer.cornerRadius = 15.0
        restartButton.layer.borderColor = UIColor.grayColor().CGColor
        restartButton.addTarget(self, action: "restart", forControlEvents: .TouchUpInside)
        return restartButton
    }()
    /// gameover的返回主页的button
    private lazy var backHomeButton:UIButton = {
        let backHomeButton = UIButton()
        backHomeButton.bounds = CGRectMake(0,0,200,30)
        
        backHomeButton.setTitle("返回主页", forState: .Normal)
        backHomeButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
        backHomeButton.layer.borderWidth = 2.0
        backHomeButton.layer.cornerRadius = 15.0
        backHomeButton.layer.borderColor = UIColor.grayColor().CGColor
        backHomeButton.addTarget(self, action: "backHome", forControlEvents: .TouchUpInside)
        return backHomeButton
    }()
    
    
    //懒加载一个倒计时view
    private lazy var countDownView:CLCountdownView = {
        let countDownView = CLCountdownView.init(frame: ScreenSize)
        countDownView.backgroundColor = UIColor.blueColor()
        //倒计时的数字
        countDownView.startNumber = 0
        countDownView.numberFont = UIFont(name: "DIN Condensed", size: 30)
        countDownView.numberColor = UIColor.cyanColor()
        
        countDownView.finishText = "GO"
        countDownView.finishFont = UIFont.boldSystemFontOfSize(30)
        return countDownView
    }()
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
